<%@ page import="fm.cache.ConfigCache" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%--
  Created by IntelliJ IDEA.
  User: CM
  Date: 17/6/2
  Time: 上午12:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文章管理</title>
    <link href="${ctx}/resources/pagination/style/pagination.css" rel="stylesheet" type="text/css">
    <link href="${ctx}/resources/pagination/style/common.css" rel="stylesheet" type="text/css">
    <jsp:include page="../../common/header.jsp"></jsp:include>
    <jsp:include page="../../common/cloud-head.jsp"></jsp:include>
    <jsp:include page="../../common/dt.jsp"></jsp:include>
    <script type="text/javascript" src="${ctx}/resources/pagination/script/jquery.pagination.js"></script>
    <style>
        #mainTable label.control-label.col-md-3 {
            min-width: 8rem;
        }

        .code-box {
            text-align: center;
        }

        .code-box > p {
            font-size: 2.6rem !important;
            margin: 1rem auto;
            color: green;
        }

        .code-box > p:before {
            content: '需支付'
        }

        .code-box canvas {
            display: block !important;
            margin: 0 auto !important;
        }

        div#qrcodePreview {
            display: block !important;
            height: auto !important;
            text-align: center;
            width: 100% !important;
        }

        .tip-content ul li {
            list-style: decimal;
            margin-left: 3rem;
        }
    </style>
</head>
<body>
<div class="col-md-12">
    <div class="card">
        <div class="card-action">
            <label>资讯配置</label>
            <button class="btn btn-primary" data-toggle="modal" data-target="addDialog"
                    onclick="initArticle();$('#addDialog').modal('show')">添加资讯
            </button>
        </div>
        <div class="card-action">
            <div class="form-group normal col-md-3">
                <label>查询关键字:</label>
                <input type="text" value="" id="keyword" name="keyword"/>

            </div>
            <shiro:hasRole name="all">
                <div class="form-group normal col-md-3">

                    <label>发布人:</label>
                    <select name="userId" id="userId" class="chosen-select" style="max-width:15rem;">
                        <option value="<%=ConfigCache.getConfig("DEFAULT_UUID")%>" selected>系统管理员</option>
                        <c:forEach items="${merchantList}" var="merchant">
                            <option value="${merchant.id}">${merchant.companyName}</option>
                        </c:forEach>
                    </select>
                </div>
            </shiro:hasRole>
            <button class="btn btn-primary" onclick="loadData();">查询
            </button>
        </div>
        <div class="card-content">
            <table id="mainTable" cellpadding="0" cellspacing="0" border="0" class="auto-table">
                <thead>
                <tr>
                    <th>文章标题</th>
                    <td>文章副标题</td>
                    <td>文章封面</td>
                    <td>发布时间</td>
                    <shiro:hasRole name="all">
                        <td>发布人</td>
                    </shiro:hasRole>
                    <td>发布板块</td>
                    <td>是否置顶</td>
                    <td>操作</td>
                </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
            <input type="hidden" name="pageNum" id="pageNum" value="1"/>
            <input type="hidden" name="pageSize" id="pageSize" value="10"/>
            <input type="hidden" name="total" id="total" value=""/>

            <div class="pagination pagination-right pagination-small" id="pagination">

            </div>
        </div>
    </div>
</div>


<div class="modal fade" id="addDialog" style="width:800px;height:580px;" tabindex="-1" role="dialog"
     aria-labelledby="articleLabel" aria-hidden="true">
    <div class="modal-dialog" style="width:800px;height:580px;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="articleLabel">
                    添加文章
                </h4>
            </div>
            <div class="modal-body" style="widht:720px;height: 320px;overflow-y: scroll">
                <input type="hidden" id="article_id" name="article_id">
                <div class="form-group">
                    <label>文章标题</label>
                    <input type="text" value="" placeholder="请输入文章标题" name="main_title" id="main_title"/>
                </div>
                <div class="form-group">
                    <label>文章副标题</label>
                    <input type="text" value="" placeholder="请输入文章副标题" name="sub_title" id="sub_title"/>
                </div>
                <div class="form-group">
                    <label>文章封面</label>
                    <img id="img-preview" name="img-preview" class="img_upload_preview"
                         for="img-file" data-target="img-val" src=""
                         onclick="$('#img-file').click()"
                         onerror="this.src='${ctx}/resources/ueditor/dialogs/image/images/image.png'"/>
                    <input id="img-file" type="file" name="img-file" style="display: none;"
                           onchange="uploadFile('img-file','img-preview','portal_img','image')"/>
                    <input name="portal_img" id="portal_img" type="hidden">
                </div>
                <div class="form-group" id="areaSelectBox">
                    <label>发布版块</label>
                    <select name="section_id" id="section_id" class="chosen-select">
                        <c:forEach items="${sectionList}" var="section">
                            <option value="${section.id}">${section.sectionName}</option>
                        </c:forEach>
                    </select>
                </div>
                <div class="row" style="margin-bottom: 30px;">
                    <hr>
                    <label>文章内容</label>
                    <script id="container" name="content" type="text/plain"></script>
                    <script type="text/javascript">
                        var ue = UE.getEditor('container', {
                            autoHeight: false,
                            maxFrameHeight: 350,
                            initialFrameHeight: 350,
                            initialFrameWidth: 700
                        });
                    </script>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消
                </button>
                <button type="button" class="btn btn-primary" onclick="addArticle()">
                    提交
                </button>
            </div>
        </div>
    </div>
</div>
<jsp:include page="template/article-template.jsp"></jsp:include>
<jsp:include page="../shop/content/common-tmpl.jsp"></jsp:include>
<script src="${ctx}/resources/script/common.js" type="text/javascript"></script>

<script>
    var sectionSelect = {};
    <c:forEach items="${sectionList}" var="section">
    sectionSelect["${section.id}"] = "${section.sectionName}";
    </c:forEach>

    if (isEmpty(sectionSelect)) {
        bootbox.confirm({
            title: '配置提示',
            message: '资讯模块尚未配置任何版块信息，将无法添加文章，请先添加版块信息。点击"确定"跳转到版块配置页面',
            buttons: {
                confirm: {
                    label: '确定'
                },
                cancel: {
                    label: '取消'
                }
            },
            callback: function (confirm) {
                if (confirm) {
                    window.location.href = ctx + '/sectionMgr/index';
                } else {

                }
            }
        });
    }


    function initArticle() {
        $("#article_id").val("");
        $("#main_title").val("");
        $("#sub_title").val("");
        ue.setContent("");
        $("#portal_img").val("");
        $("#section_id").val("");
        $("#img-preview").attr("src", "");
    }

    $(function () {
        loadData();
    })

    function pageLoad() {
        var pageCount = Math.ceil((parseInt(($('#total').val() || 0)) / parseInt($("#pageSize").val() || 10)));
        $("#pagination").pagination({
            pageCount: pageCount,
            pageSize: parseInt($("#pageSize").val() || 10),
            totalCount: parseInt($("#total").val()),
            current: parseInt($("#pageNum").val()),
            jump: true,
            coping: true,
            homePage: '首页',
            endPage: '末页',
            prevContent: '上页',
            nextContent: '下页',
            callback: function (that) {
                //console.log("that:%o", that);
                $("#pageNum").val(that.getCurrent());
                loadData();
                that.setCurrentPage()
            }
        })
    }

    function loadData() {
        var data = {
            pageNum: $("#pageNum").val(),
            pageSize: $("#pageSize").val(),
            type: 1
        };
        if (!isEmpty($("#keyword").val())) {
            data["keyword"] = encodeURI($("#keyword").val());
        }

        if (!isEmpty($("#userId").val())) {
            data["uuid"] = $("#userId").val();
        }

        asyncAjax({
            url: ctx + "/article/getArticleList?" + $.param(data).replace(/(%5D|%5B)/g, ""),
            type: "post",
            beforeSend: function (req) {
                $("#mainTable tbody").html("<tr><td colspan=\"7\"><div class=\"alert alert-warning\">正在请求数据...</div></td></tr>");
            },
            success: function (res) {
                if (res["result"] == "0") {
                    if (res["data"].length <= 0) {
                        $("#mainTable tbody").html("<tr><td colspan=\"7\"><div class=\"alert alert-warning\">没有找到符合条件的数据！</div></td></tr>");
                    } else {
                        $("#total").val(res["total"] || 0);
                        $("#mainTable tbody").html("");
                        for (var i in res["data"]) {
                            res["data"][i]["sectionName"] = sectionSelect[res["data"][i]["section_id"]];
                        }
                        $("#dataTmpl").tmpl(res["data"]).appendTo("#mainTable tbody");
                        pageLoad();
                    }
                } else {

                }
            }
        })
    }

    function addArticle() {
        var content = ue.getContent();
        content = content.replace(/max-width:(\s|\d)+(%|px)\s{0}(!important){0,1}/g, "max-width:100% !important");
        //console.log("resole max-width problems");
        var data = {
            id: $("#article_id").val() || "",
            main_title: $("#main_title").val() || "",
            sub_title: $("#sub_title").val() || "",
            section_id: $("#section_id").val() || "",
            sectionName: $("#section_id").val() ? sectionSelect[$("#section_id").val()] : "",
            content: content,
            portal_img: $("#portal_img").val(),
            type: 1
        }
        if (isEmpty(data["portal_img"])) {
            bootbox.alert("请上传文章封面!");
            return;
        }
        asyncAjax({
            url: ctx + "/article/mergeArticle",
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify(data),
            success: function (res) {
                //console.log("res:%o", res);
                if (res["result"] == "0") {
                    bootbox.alert("操作成功");
                    $("#addDialog").modal("hide");

                    loadData();
                } else {
                    bootbox.alert(res["msg"]);
                }
            }
        })
    }

    function editArticle(id) {
        var params = {
            "article_id": id
        }
        $.post(ctx + "/article/getArticleInfo", params, function (res) {
            if (res.result == 0) {
                $("#article_id").val(res.data.id);
                $("#main_title").val(res.data.main_title);
                $("#sub_title").val(res.data.sub_title);
                ue.setContent(res.data.content);
                $("#portal_img").val(res.data.portal_img);
                $("#section_id").val(res.data.section_id);
                $("#img-preview").attr("src", res.data.portal_img);
                $('#addDialog').modal('show');
            } else {
                alert(res.msg)
            }
        });

    }

    function untopArticle(id, adOption) {
        var params = {
            "id": id
        }
        $.post(ctx + "/article/ad/remove/" + adOption, params, function (res) {
            if (res.result == 0) {
                loadData();
            } else {
                alert(res.msg)
            }
        });
    }

    function topArticle(id, adOption) {
        bootbox.alert({
            title: '文章列表置顶推广',
            message: '<div><label>推广时长</label>' +
            '<select id="resolveKey" name="resolveKey">' +
            '<option value="oneWeek">一周</option>' +
            '<option value="oneMonth">一个月</option>' +
            '<option value="threeMonth">三个月</option>' +
            '<option value="halfYear">半年</option>' +
            '<option value="year">一年</option>' +
            '</select></div>',
            callback: function (res) {
                var resolveKey = $("#resolveKey").val()
                if (!resolveKey) {
                    bootbox.alert("请选择推广时间！");
                    return -1;
                }
                var params = {
                    "id": id,
                    resolveKey: resolveKey
                }
                asyncAjax({
                    url: ctx + "/article/ad/web/" + adOption, data: params, success: function (res) {
                        if (res.result == 0) {
                            if (res.data.codeUrl) {
                                res.data.total = res.total;
                                bootbox.alert({
                                    title: "扫码支付",
                                    message: $("#payTmpl").tmpl(res.data).html(),
                                    success: function (res) {
                                        bootbox.alert("支付后如果未看到推广状态更新，请稍后再刷新页面查看，支付结果更新可能粗在一定的延时。")
                                        loadData();
                                    }
                                });
                                setTimeout(function () {
                                    $("#qrcodePreview").qrcode(res.data.codeUrl);
                                }, 1000)
                            }
                            //console.log("top response:%o", res);
                            debugger;
                        } else {
                            alert(res.msg)
                        }
                    }
                });

            }
        })

    }

    function delArticle(id) {
        if (!confirm("确认要删除？")) {
            return;
        }
        var params = {
            "id": id
        }
        $.post(ctx + "/article/delArticle", params, function (res) {
            if (res.result == 0) {
                loadData();
            } else {
                alert(res.msg)
            }
        });
    }

</script>
</body>
</html>
